package com.yuyue.springFramework.note03.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Cglib代理
 */
public class CostCglib {
    public <T> T createProxy(Class<T> target){
        //创建增强类
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(target);
        //设置拦截器
        enhancer.setCallback(new MethodInterceptor() {
            //重写拦截器方法
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                long startTime = System.nanoTime();

                //调用原方法并获取返回值
                Object result = methodProxy.invokeSuper(o,objects);

                long endTime = System.nanoTime();
                System.out.println(method.getName() + "耗时（纳秒）：" + (endTime - startTime));

                return result;
            }
        });

        //返回代理类
        return (T) enhancer.create();
    }
}
